<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频生成器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 15px;
            line-height: 1.4;
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
        }
        .btn {
            background-color: #4CAF50;
            color: white;
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn:hover {
            background-color: #45a049;
        }
        .btn-small {
            padding: 4px 8px;
            font-size: 0.9em;
            background-color: #2196F3;
        }
        .btn-small:hover {
            background-color: #0b7dda;
        }
        #result {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: none;
        }
        #videoPlayer {
            width: 100%;
            max-width: 640px;
            margin: 0 auto;
            display: block;
        }
        .error {
            color: red;
            font-weight: bold;
        }
        .loading {
            text-align: center;
            margin: 15px 0;
            display: none;
        }
        .segments-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }
        .segments-table th, .segments-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
            vertical-align: middle;
        }
        .segments-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .segments-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .segments-table tr:hover {
            background-color: #f1f1f1;
        }
        .file-input-container {
            display: flex;
            align-items: center;
        }
        .file-input-container input[type="file"] {
            max-width: 220px;
        }
        .file-name {
            margin-left: 5px;
            font-size: 0.9em;
            color: #666;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 150px;
        }
        .action-buttons {
            display: flex;
            justify-content: space-between;
            margin: 15px 0;
        }
        .segment-number {
            font-weight: bold;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>视频生成器</h1>
    
    <form id="uploadForm" enctype="multipart/form-data">
        <table class="segments-table" id="segmentsTable">
            <thead>
                <tr>
                    <th width="5%">#</th>
                    <th width="30%">背景图片</th>
                    <th width="30%">音频文件</th>
                    <th width="35%">字幕文件 (SRT格式)</th>
                </tr>
            </thead>
            <tbody id="segmentsContainer">
                <tr class="segment" data-index="0">
                    <td class="segment-number">1</td>
                    <td>
                        <div class="file-input-container">
                            <input type="file" id="image-0" name="image-0" accept="image/*" required>
                            <span class="file-name" id="image-name-0"></span>
                        </div>
                    </td>
                    <td>
                        <div class="file-input-container">
                            <input type="file" id="audio-0" name="audio-0" accept="audio/*" required>
                            <span class="file-name" id="audio-name-0"></span>
                        </div>
                    </td>
                    <td>
                        <div class="file-input-container">
                            <input type="file" id="srt-0" name="srt-0" accept=".srt" required>
                            <span class="file-name" id="srt-name-0"></span>
                            <button type="button" class="btn btn-small test-srt-btn" data-index="0">测试</button>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>

        <div class="action-buttons">
            <div>
                <button type="button" id="addSegment" class="btn btn-small" style="background-color: #4CAF50;">添加片段</button>
                <button type="button" id="removeSegment" class="btn btn-small" style="background-color: #f44336;">删除片段</button>
            </div>
            <button type="submit" class="btn">生成视频</button>
        </div>
    </form>
    
    <div id="srtTestResult" style="display: none; margin-top: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
        <h3>字幕测试结果</h3>
        <div id="srtContent"></div>
    </div>
    
    <div class="loading" id="loading">
        <p>正在生成视频，请稍候...</p>
    </div>
    
    <div id="result">
        <h2>生成结果</h2>
        <div id="videoContainer">
            <video id="videoPlayer" controls preload="auto" playsinline width="100%">
                您的浏览器不支持 HTML5 视频播放。
                <source type="video/mp4">
            </video>
        </div>
    </div>
    
    <script>
        // 全局变量，跟踪当前片段数量
        let segmentCount = 1;
        
        // 文件选择事件处理
        function handleFileSelect(event) {
            const fileInput = event.target;
            const fileNameSpan = document.getElementById(fileInput.id.replace(/-\d+$/, '-name') + '-' + fileInput.id.match(/-(\d+)$/)[1]);
            if (fileInput.files.length > 0) {
                fileNameSpan.textContent = fileInput.files[0].name;
            } else {
                fileNameSpan.textContent = '';
            }
        }
        
        // 为初始文件输入添加事件监听器
        document.getElementById('image-0').addEventListener('change', handleFileSelect);
        document.getElementById('audio-0').addEventListener('change', handleFileSelect);
        document.getElementById('srt-0').addEventListener('change', handleFileSelect);
        
        // 添加片段按钮
        document.getElementById('addSegment').addEventListener('click', function() {
            const newIndex = segmentCount;
            segmentCount++;
            
            const segmentRow = document.createElement('tr');
            segmentRow.className = 'segment';
            segmentRow.dataset.index = newIndex;
            
            segmentRow.innerHTML = `
                <td class="segment-number">${segmentCount}</td>
                <td>
                    <div class="file-input-container">
                        <input type="file" id="image-${newIndex}" name="image-${newIndex}" accept="image/*" required>
                        <span class="file-name" id="image-name-${newIndex}"></span>
                    </div>
                </td>
                <td>
                    <div class="file-input-container">
                        <input type="file" id="audio-${newIndex}" name="audio-${newIndex}" accept="audio/*" required>
                        <span class="file-name" id="audio-name-${newIndex}"></span>
                    </div>
                </td>
                <td>
                    <div class="file-input-container">
                        <input type="file" id="srt-${newIndex}" name="srt-${newIndex}" accept=".srt" required>
                        <span class="file-name" id="srt-name-${newIndex}"></span>
                        <button type="button" class="btn btn-small test-srt-btn" data-index="${newIndex}">测试</button>
                    </div>
                </td>
            `;
            
            document.getElementById('segmentsContainer').appendChild(segmentRow);
            
            // 为新添加的文件输入添加事件监听器
            document.getElementById(`image-${newIndex}`).addEventListener('change', handleFileSelect);
            document.getElementById(`audio-${newIndex}`).addEventListener('change', handleFileSelect);
            document.getElementById(`srt-${newIndex}`).addEventListener('change', handleFileSelect);
            
            // 为新添加的测试字幕按钮添加事件监听器
            segmentRow.querySelector('.test-srt-btn').addEventListener('click', handleTestSrt);
        });
        
        // 删除片段按钮
        document.getElementById('removeSegment').addEventListener('click', function() {
            if (segmentCount > 1) {
                const segments = document.querySelectorAll('.segment');
                const lastSegment = segments[segments.length - 1];
                lastSegment.remove();
                segmentCount--;
            } else {
                alert('至少需要保留一个片段');
            }
        });
        
        // 处理字幕测试
        function handleTestSrt(event) {
            const index = event.target.dataset.index;
            const srtFile = document.getElementById(`srt-${index}`).files[0];
            
            if (!srtFile) {
                alert('请先选择字幕文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('srt', srtFile);
            
            // 显示加载中
            document.getElementById('srtTestResult').style.display = 'block';
            document.getElementById('srtContent').innerHTML = '<p>正在解析字幕文件...</p>';
            
            // 发送请求
            fetch('/test-srt', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    document.getElementById('srtContent').innerHTML = '<p class="error">错误: ' + data.error + '</p>';
                } else {
                    let html = '<p>成功解析 ' + data.subtitle_count + ' 条字幕</p>';
                    html += '<table style="width:100%; border-collapse: collapse;">';
                    html += '<tr><th style="border:1px solid #ddd; padding:8px;">序号</th><th style="border:1px solid #ddd; padding:8px;">开始时间</th><th style="border:1px solid #ddd; padding:8px;">结束时间</th><th style="border:1px solid #ddd; padding:8px;">文本</th></tr>';
                    
                    data.subtitles.forEach(sub => {
                        html += '<tr>';
                        html += '<td style="border:1px solid #ddd; padding:8px;">' + sub.index + '</td>';
                        html += '<td style="border:1px solid #ddd; padding:8px;">' + sub.start + '</td>';
                        html += '<td style="border:1px solid #ddd; padding:8px;">' + sub.end + '</td>';
                        html += '<td style="border:1px solid #ddd; padding:8px;">' + sub.text + '</td>';
                        html += '</tr>';
                    });
                    
                    html += '</table>';
                    document.getElementById('srtContent').innerHTML = html;
                }
            })
            .catch(error => {
                document.getElementById('srtContent').innerHTML = '<p class="error">请求失败: ' + error.message + '</p>';
            });
        }
        
        // 为初始的测试字幕按钮添加事件监听器
        document.querySelectorAll('.test-srt-btn').forEach(btn => {
            btn.addEventListener('click', handleTestSrt);
        });
        
        // 处理视频生成表单提交
        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 显示加载提示
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').style.display = 'none';
            
            // 创建FormData对象
            const formData = new FormData();
            
            // 获取所有片段的文件
            const segments = document.querySelectorAll('.segment');
            formData.append('segment_count', segments.length);
            
            segments.forEach((segment, index) => {
                const imageFile = document.getElementById(`image-${segment.dataset.index}`).files[0];
                const audioFile = document.getElementById(`audio-${segment.dataset.index}`).files[0];
                const srtFile = document.getElementById(`srt-${segment.dataset.index}`).files[0];
                
                if (!imageFile || !audioFile || !srtFile) {
                    alert(`片段 #${index + 1} 缺少必要的文件`);
                    document.getElementById('loading').style.display = 'none';
                    return;
                }
                
                formData.append(`image-${index}`, imageFile);
                formData.append(`audio-${index}`, audioFile);
                formData.append(`srt-${index}`, srtFile);
            });
            
            // 发送请求
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载提示
                document.getElementById('loading').style.display = 'none';
                
                if (data.error) {
                    // 显示错误信息
                    document.getElementById('result').style.display = 'block';
                    document.getElementById('result').innerHTML = '<p class="error">错误: ' + data.error + '</p>';
                } else if (data.url) {
                    // 显示视频
                    document.getElementById('result').style.display = 'block';
                    const videoPlayer = document.getElementById('videoPlayer');
                    if (videoPlayer) {
                        console.log('Setting video src to:', data.url);
                        videoPlayer.src = data.url;
                        
                        // 添加视频加载事件监听器
                        videoPlayer.onloadeddata = function() {
                            console.log('视频加载成功');
                        };
                        
                        // 添加视频错误事件监听器
                        videoPlayer.onerror = function(e) {
                            console.error('视频加载失败:', e);
                            document.getElementById('result').innerHTML = 
                                '<p class="error">视频加载失败</p>' +
                                '<p>错误代码: ' + (videoPlayer.error ? videoPlayer.error.code : 'unknown') + '</p>' +
                                '<p>视频URL: ' + data.url + '</p>' +
                                '<p>文件名: ' + data.filename + '</p>' +
                                '<p><a href="' + data.url + '" target="_blank">直接访问视频</a></p>';
                        };
                    } else {
                        console.error('videoPlayer element not found');
                        document.getElementById('result').innerHTML = '<p class="error">无法显示视频播放器</p>';
                    }
                }
            })
            .catch(error => {
                // 隐藏加载提示
                document.getElementById('loading').style.display = 'none';
                
                // 显示错误信息
                document.getElementById('result').style.display = 'block';
                document.getElementById('result').innerHTML = '<p class="error">请求失败: ' + error.message + '</p>';
            });
        });
    </script>
</body>
</html>